package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * Title  : 144. Binary Tree Preorder Traversal
 * Source : https://leetcode.cn/problems/binary-tree-preorder-traversal/
 * Author : XrazYang
 * Date   : 2023-09-05
 */

public class LeetCode_144 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        if (root == null) {
            return results;
        }
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        sta.push(root);
        while (!sta.isEmpty()) {
            TreeNode node = sta.pop();
            results.add(node.val);
            if (node.right != null) {
                sta.push(node.right);
            }
            if (node.left != null) {
                sta.push(node.left);
            }
        }
        return results;
    }
}
